package com.xunwulian.web.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xunwulian.api.dto.BaseResponse;
import com.xunwulian.api.iface.AppAPI;
import com.xunwulian.api.iface.CardAPI;
import com.xunwulian.api.iface.ConfigAPI;
import com.xunwulian.api.iface.UserAPI;
import com.xunwulian.base.dao.SmsGprsBalanceDao;
import com.xunwulian.base.entity.AppEntity;
import com.xunwulian.base.entity.SmsGprsBalanceEntity;
import com.xunwulian.base.entity.User;
import com.xunwulian.base.util.ExcelUtil2;
import com.xunwulian.base.util.FileUtil;
import com.xunwulian.base.util.PageData;
import com.xunwulian.web.util.*;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/tool")
public class ToolController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(ToolController.class);

    @Reference
    private CardAPI cardAPI;
    @Reference
    private AppAPI appAPI;
    @Reference
    private UserAPI userAPI;
    @Reference
    private ConfigAPI configAPI;

    @Autowired
    private SmsGprsBalanceDao smsGprsBalanceDao;

    private FileUtil fileUtil = new FileUtil();

    private ExcelUtil2 excelUtil2 = new ExcelUtil2();


    /**
     * 数据生成页面
     *
     * @return
     */
    @RequestMapping("generate")
    public ModelAndView generate() {
        ModelAndView mav = new ModelAndView("system/tools/generate");

        return mav;
    }


    /**
     * 短信流量数据导入
     *
     * @return
     */
    @RequestMapping("gprsSmsImport")
    public ModelAndView gprsSmsImport() {
        ModelAndView mav = new ModelAndView("system/tools/gprsSmsImport");

        BaseResponse<List<AppEntity>> result = appAPI.getAppList();
        mav.addObject("varList", result.getData());

        return mav;
    }

    /**
     * 上传
     *
     * @param upload
     * @param request
     * @return
     */
    @RequestMapping(value = "uploadGprsSms", method = RequestMethod.POST)
    public ModelAndView uploadGprsSms(MultipartFile upload, HttpServletRequest request) {

        try {
            // 获取文件保存的根路径
            String uploadFilePath = request.getSession().getServletContext().getRealPath(configAPI.getByCode(Const.UPLOAD_PATH).getValue());
            String targetFileName = uploadFile(upload, uploadFilePath);

            new Thread(() -> {
                List<ExcelUtil2.ExcelColumnWrapper> ecws = new ArrayList<>();
                ecws.add(new ExcelUtil2.ExcelColumnWrapper(0, "date"));
                ecws.add(new ExcelUtil2.ExcelColumnWrapper(1, "msisdn"));
                ecws.add(new ExcelUtil2.ExcelColumnWrapper(4, "gprs"));
                ecws.add(new ExcelUtil2.ExcelColumnWrapper(5, "gprsPkg"));
                ecws.add(new ExcelUtil2.ExcelColumnWrapper(6, "gprsBalance"));
                ecws.add(new ExcelUtil2.ExcelColumnWrapper(7, "sms"));
                ecws.add(new ExcelUtil2.ExcelColumnWrapper(8, "smsPkg"));
                ecws.add(new ExcelUtil2.ExcelColumnWrapper(9, "smsBalance"));

                Workbook workbook = excelUtil2.loadExcel(targetFileName);
                List<SmsGprsBalanceEntity> smsGbes = excelUtil2.parseExcel(workbook, SmsGprsBalanceEntity.class, ecws);

                int si = smsGbes.size();
                int index = 0;
                for (SmsGprsBalanceEntity smsGbe : smsGbes) {
                    index++;
                    smsGprsBalanceDao.insert4Import(smsGbe);
                    logger.debug("共有" + si + "条数据_____已插入" + index + "条数据...");
                }
            }).start();

        } catch (Exception e) {
            e.printStackTrace();
        }
        ModelAndView mv = getModelAndView();
        PageData pd = getPageData();
        mv.setViewName("system/tools/gprsSmsImport");
        mv.addObject("pd", pd);

        return mv;
    }

    /**
     * 上传文件
     */
    private String uploadFile(MultipartFile multipartFile, String saveFilePath) {
        try {
            FileUtil fileUtil = new FileUtil();
            // 获取文件的文件名
            String fileName = fileUtil.createFileName(multipartFile.getOriginalFilename());
            // 创建保存文件的根目录
            fileUtil.createFileDirectory(saveFilePath);
            File targetFile = new File(saveFilePath, fileName);
            //保存
            multipartFile.transferTo(targetFile);
            return targetFile.getCanonicalPath();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 去接口测试页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/interfaceTest")
    public ModelAndView editEmail() throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pd = this.getPageData();
        mv.setViewName("system/tools/interfaceTest");
        mv.addObject("pd", pd);
        return mv;
    }

    /**
     * 接口内部请求
     *
     * @return
     */
    @RequestMapping(value = "/severTest")
    @ResponseBody
    public Object severTest() {
        Map<String, String> map = new HashMap<String, String>();
        PageData pd = this.getPageData();
        String errInfo = "success", str = "", rTime = "";
        try {
            long startTime = System.currentTimeMillis(); // 请求起始时间_毫秒
            URL url = new URL(pd.getString("serverUrl"));
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setRequestMethod(pd.getString("requestMethod")); // 请求类型
            // POST
            // or
            // GET
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    url.openStream()));
            long endTime = System.currentTimeMillis(); // 请求结束时间_毫秒
            String temp = "";
            while ((temp = in.readLine()) != null) {
                str = str + temp;
            }
            rTime = String.valueOf(endTime - startTime);
        } catch (Exception e) {
            errInfo = "error";
        }
        map.put("errInfo", errInfo); // 状态信息
        map.put("result", str); // 返回结果
        map.put("rTime", rTime); // 服务器请求时间 毫秒
        return AppUtil.returnObject(new PageData(), map);
    }

    /**
     * 发送邮件页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/goSendEmail")
    public ModelAndView goSendEmail() throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pd = this.getPageData();
        mv.setViewName("system/tools/email");
        mv.addObject("pd", pd);
        return mv;
    }

    /**
     * 二维码页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/goTwoDimensionCode")
    public ModelAndView goTwoDimensionCode() throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pd = this.getPageData();
        mv.setViewName("system/tools/twoDimensionCode");
        mv.addObject("pd", pd);
        return mv;
    }

    /**
     * 生成二维码
     *
     * @return
     */
    @RequestMapping(value = "/createTwoDimensionCode")
    @ResponseBody
    public Object createTwoDimensionCode() {
        Map<String, String> map = new HashMap<String, String>();
        PageData pd = this.getPageData();
        String errInfo = "success", encoderImgId = this.get32UUID() + ".png"; // encoderImgId此处二维码的图片名
        String encoderContent = pd.getString("encoderContent"); // 内容
        if (null == encoderContent) {
            errInfo = "error";
        } else {
            try {
                String filePath = PathUtil.getClasspath()
                        + Const.FILEPATHTWODIMENSIONCODE + encoderImgId; // 存放路径
                TwoDimensionCode.encoderQRCode(encoderContent, filePath, "png"); // 执行生成二维码
            } catch (Exception e) {
                errInfo = "error";
            }
        }
        map.put("result", errInfo); // 返回结果
        map.put("encoderImgId", encoderImgId); // 二维码图片名
        return AppUtil.returnObject(new PageData(), map);
    }

    /**
     * 解析二维码
     *
     * @return
     */
    @RequestMapping(value = "/readTwoDimensionCode")
    @ResponseBody
    public Object readTwoDimensionCode() {
        Map<String, String> map = new HashMap<String, String>();
        PageData pd = this.getPageData();
        String errInfo = "success", readContent = "";
        String imgId = pd.getString("imgId");// 内容
        if (null == imgId) {
            errInfo = "error";
        } else {
            try {
                String filePath = PathUtil.getClasspath()
                        + Const.FILEPATHTWODIMENSIONCODE + imgId; // 存放路径
                readContent = TwoDimensionCode.decoderQRCode(filePath);// 执行读取二维码
            } catch (Exception e) {
                errInfo = "error";
            }
        }
        map.put("result", errInfo); // 返回结果
        map.put("readContent", readContent); // 读取的内容
        return AppUtil.returnObject(new PageData(), map);
    }

    /**
     * 多级别树页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/ztree")
    public ModelAndView ztree() throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pd = this.getPageData();
        mv.setViewName("system/tools/ztree");
        mv.addObject("pd", pd);
        return mv;
    }

    /**
     * 地图页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/map")
    public ModelAndView map() throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pd = this.getPageData();
        mv.setViewName("system/tools/map");
        mv.addObject("pd", pd);
        return mv;
    }

    /**
     * 获取地图坐标页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/mapXY")
    public ModelAndView mapXY() throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pd = this.getPageData();
        mv.setViewName("system/tools/mapXY");
        mv.addObject("pd", pd);
        return mv;
    }

    /**
     * 根据经纬度计算距离
     *
     * @return
     */
    @RequestMapping(value = "/getDistance")
    @ResponseBody
    public Object getDistance() {
        Map<String, String> map = new HashMap<String, String>();
        PageData pd = this.getPageData();
        String errInfo = "success", distance = "";
        try {
            distance = MapDistance.getDistance(pd.getString("ZUOBIAO_Y"),
                    pd.getString("ZUOBIAO_X"), pd.getString("ZUOBIAO_Y2"),
                    pd.getString("ZUOBIAO_X2"));
        } catch (Exception e) {
            errInfo = "error";
        }
        map.put("result", errInfo); // 返回结果
        map.put("distance", distance); // 距离
        return AppUtil.returnObject(new PageData(), map);
    }

    /**
     * 打印测试页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/printTest")
    public ModelAndView printTest() throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        mv.setViewName("system/tools/printTest");
        mv.addObject("pd", pd);
        return mv;
    }

    /**
     * 打印预览页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/printPage")
    public ModelAndView printPage() throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pd = this.getPageData();
        ;
        mv.setViewName("system/tools/printPage");
        mv.addObject("pd", pd);
        return mv;
    }

}